<!--
 * @Author: 肖芬芳 1911683843@qq.com
 * @Date: 2022-12-08 11:43:30
 * @LastEditors: 肖芬芳 1911683843@qq.com
 * @LastEditTime: 2022-12-13 16:34:27
 * @FilePath: \blog\src\views\admin\goods\classify\components\SecondClassDrawer.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <el-drawer
    v-model="showDrawer"
    :show-close="false"
    size="90%"
    :with-header="false"
    @open="openDrawer"
  >
    <el-button type="primary" @click="closeDrawer" style="margin-bottom: 16px">
      返回
    </el-button>
    <formSearch
      :form-item="formItem"
      :form-data="formData"
      :add-btn="true"
      :reset-btn="true"
      @searchForm="searchForm"
      @clearForm="clearForm"
      @addData="showDialog('新增')"
    />

    <tableList
      :table-title="tableTitle"
      :table-data="tableData"
      :pageInfo="pageInfo"
      :showExpand="false"
      @changeStatus="changeStatus"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
      @prevClick="prevClick"
      @nextClick="nextClick"
    >
      <template #btn="scope">
        <el-button type="text" @click="handleEdit(scope.slotval)"
          >编辑</el-button
        >
      </template>
    </tableList>

    <el-dialog
      custom-class="dialogClass"
      v-model="dialogVisible"
      :title="dialogTitle"
    >
      <amForm
        ref="baseForm"
        :form-item="dialogFormItem"
        :form-data="dialogFormData"
      >
      </amForm>
      <div style="width: 100%; border: 1px solid #f0f2f5"></div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="clostBtn">取消</el-button>
          <el-button
            type="primary"
            @click="
              dialogTitle == '新增'
                ? submitForm(baseForm.formRef)
                : modifyForm(baseForm.formRef)
            "
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </el-drawer>
</template>


<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { formatTime } from "@/util/base/formatTime";
import { ElMessage, FormInstance } from "element-plus";
import { secondClassDrawer } from "./option";
import {SearchList} from "../params/secondClassParams"
import {ClassListVo} from "../Vo/classifyVo"
import SecondClassServiceApi from "../api/secondClassServiceApi";
const secondClassServiceApi = new SecondClassServiceApi();

interface Props {
  showDrawer: boolean;
  id: string;
}
const props = withDefaults(defineProps<Props>(), {
  showDrawer: false,
  id: "",
});

// 搜索表单
const formItem = secondClassDrawer.formItem;
const formData = reactive<any>({});
const emit = defineEmits(["closeDrawer"]);

// 表格
const tableTitle = secondClassDrawer.tableTitle;
const tableData = ref();
const pageInfo = reactive({
  currentPage: 1,
  pageSize: 10,
  totalCount: 30,
});

// 弹框
const secondClassId = ref("");
const baseForm = ref<HTMLElement | any>();
const dialogVisible = ref(false);
const dialogTitle = ref("");
const dialogFormItem = secondClassDrawer.dialogFormItem;
const dialogFormData = reactive({
  secondClassName: "",
});

const openDrawer = () => {
  getData();
};

const closeDrawer = () => {
  emit("closeDrawer", false);
};

const getData = async () => {
  if(formData.startTime!=undefined){
    formData.startTime=new Date(formData.startTime).getTime()
  }
  if(formData.endTime!=undefined){
    formData.endTime=new Date(formData.endTime).getTime()+3600 * 1000 * 24-1
  }

  // 校验日期：
  if(formData.startTime!=undefined && formData.endTime!=undefined && formData.startTime>formData.endTime){
    ElMessage.error("开始时间不能大于结束时间")
    return
  }

  let params: SearchList = {
    firstClassId: props.id,
    pageSize: pageInfo.pageSize,
    currentPage: pageInfo.currentPage,
    ...formData,
  };
  const res:any = await secondClassServiceApi.getSecondClassList(params);
  let totalCount: number = res.totalCount;
  let data: Array<Object> = res.data;
  // console.log(data);
  data.forEach((item:any) => {
    item.createTime = formatTime("YYYY年mm月dd日 HH:MM:SS", item.createTime);
  });
  tableData.value = data;
  pageInfo.totalCount = totalCount;
};

const searchForm = () => {
  getData();
};

// 重置搜索条件
const clearForm = () => {
  pageInfo.currentPage = 1;
  getData();
};

// 点击新增/编辑按钮
const showDialog = (title: string) => {
  if (title == "新增") clearDetail();
  dialogVisible.value = true;
  dialogTitle.value = title;
};

const handleEdit = async (secondClass: any) => {
  // 获取详情数据
  let detail:any = await getDetail(secondClass._id);
  dialogFormData.secondClassName = detail.secondClassName;
  secondClassId.value = secondClass._id;
  showDialog("编辑");
};

// 获取详情信息
const getDetail = async (id: string) => {
  let res = await secondClassServiceApi.detail(id);
  return res.data;
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let params = {
        firstClassId: props.id,
        ...dialogFormData,
      };
      const data = await secondClassServiceApi.addSecondClass(params);
      if (data.code == 200) {
        ElMessage.success("新增成功！");
      }
      formEl.resetFields();
      clostBtn();
    } else {
      console.log("error submit!", fields);
    }
  });
};

const modifyForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let params = {
        id:secondClassId.value,
        ...dialogFormData
      };
      const data = await secondClassServiceApi.modifySecondClass(params);
      if (data.code == 200) {
        ElMessage.success("编辑成功！");
      }
      formEl.resetFields();
      clostBtn();
    } else {
      console.log("error submit!", fields);
    }
  });
};

const clostBtn = () => {
  clearDetail();
  dialogVisible.value = false;
  baseForm.value.formRef.resetFields();
  getData()
};

// 清空详情页的数据
const clearDetail = () => {
  dialogFormData.secondClassName = "";
};

// 改变状态
const changeStatus = async (secondClassId: string) => {
  let res = await secondClassServiceApi.changeSecondStatus({ id: secondClassId });
  getData();
};

const handleSizeChange = (pageSize: number) => {
  // console.log("改变列表页面大小");
  pageInfo.pageSize = pageSize;
  getData();
};

const handleCurrentChange = (currentPage: number) => {
  // console.log("改变当前页面数字");
  pageInfo.currentPage = currentPage;
  getData();
};

const prevClick = (currentPage: number) => {
  pageInfo.currentPage = currentPage;
  getData();
};

const nextClick = (currentPage: number) => {
  pageInfo.currentPage = currentPage;
  getData();
};
</script>


<style lang="scss" scoped>
</style>